package com.bigshen.algorithm.aLinearList.solution01ReverseLinkedList;

/**
 * Reverse a singly linked list.
 *
 * Example:
 *
 * Input: 1->2->3->4->5->NULL
 * Output: 5->4->3->2->1->NULL
 *
 * 来源：力扣（LeetCode）
 * 链接：https://leetcode-cn.com/problems/reverse-linked-list
 * 著作权归领扣网络所有。商业转载请联系官方授权，非商业转载请注明出处。
 *
 * 迭代方式翻转
 */
public class Solution {

    public ListNode reverseList(ListNode head) {

        if (null == head || null == head.next) {
            return head;
        }

        ListNode prev = head;
        ListNode current = head.next;
        prev.next = null;
        while(null != current) {
            ListNode next = current.next;
            current.next = prev;
            prev = current;
            current = next;
        }

        return prev;

    }


    public static void main(String[] args) {

        ListNode head = new ListNode(1);
        ListNode node2 = new ListNode(2);
        ListNode node3 = new ListNode(3);
        ListNode node4 = new ListNode(4);
        ListNode node5 = new ListNode(5);

        head.next = node2;
        node2.next = node3;
        node3.next = node4;
        node4.next = node5;

        ListNode reverse = new Solution().reverseList(head);

        ListNode tmp = reverse;
        while (null != tmp) {
            System.out.println(tmp.val);
            tmp = tmp.next;
        }

    }

}

class ListNode {
    int val;
    ListNode next;
    ListNode(int val) {
        this.val = val;
    }
}